from sanic.views import HTTPMethodView
from sanic.response import text,json
import urllib3
import json as jn
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id,date_format
from processing.comm import sqlPaging,sqlOrder,set_status,timestamp_to_standard
from processing.Sql_DataFrom import ProJosn

class getBanner(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        html_data = request.json
        client_ip = request.ip
        user_id = request.app.ctx.user_id
        pageNum = int(request.args.get('pageNum', 1))
        type = request.args.get('type', '')
        pageSize = int(request.args.get('pageSize', 10))
        try:

            sql = f"""
                select title,target_data,target_url,subhead,image from banner where merchant_id='{user_id}' and status='{'normal'}' and type='{type}'
            """
            sql = sqlOrder(sql, 'sort', 'ASC')
            sql = sqlPaging(pageNum, pageSize, sql)
            sql_data = db.find_all(sql)
            if sql_data:
                data = ProJosn(sql_data, sql)
            else:
                data = []

            return json({'code': 200, 'message': "请求成功！",'data':{
                'list':data
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/getCategory/getCategory', error))
            return json({'code': 200, 'message': "请求成功！"})

class getGoods(HTTPMethodView):

    async def get(self, request):
        db = request.app.ctx.db

        client_ip = request.ip
        user_id = request.app.ctx.user_id
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        businessId = request.args.get('businessId', '')

        try:
            sql = f"""
                select subtitle,categoryId,goodsDetails,goodsDetailsJson,goodsName,goodsSkuJson,goodsPrice,goodsType,goodsViewCount,limitNum,memberPrice,previewUrl,retirementRule,
                rotationImgsJson,scribePrice,stockNum,contents,businessId,goods_id,paypal_type,order_type,rewardIntegral,distributionFee,
                label_ids,goodsSkuType,goods_type,goods_unit,goods_unit_num,goods_code,goods_status,goods_number,goods_barCode,goods_volume,distributionType,goods_sales,sort,gift_coupons_id,
                serviceGuarantee_id,member_see,start_shopping,reservation_startTime,reservation_endTime,is_reservation,reservation_send_time,is_reservation_endTime,goods_recommend,goods_recommend_id,
                goods_introduction,goods_distribution_text,goods_command,goods_recommend_image from goods where 
                merchant_id='{user_id}' and goods_status='{'立即上架'}' and businessId='{businessId}' or businessId=''
            """
            sql = sqlOrder(sql, 'ctime')
            sql = sqlPaging(pageNum, pageSize, sql)
            sql_data = db.find_all(sql)
            header = ['subtitle','categoryId','goodsDetails','goodsDetailsJson','goodsName','goodsSkuJson','goodsPrice','goodsType','goodsViewCount','limitNum','memberPrice','previewUrl','retirementRule',
                'rotationImgsJson','scribePrice','stockNum','contents','businessId','goods_id','paypal_type','order_type','rewardIntegral',
                      'distributionFee',
                      'label_ids', 'goodsSkuType', 'goods_type', 'goods_unit', 'goods_unit_num', 'goods_code',
                      'goods_status',
                      'goods_number', 'goods_barCode', 'goods_volume', 'distributionType', 'goods_sales', 'sort',
                      'gift_coupons_id',
                      'serviceGuarantee_id', 'member_see', 'start_shopping', 'reservation_startTime',
                      'reservation_endTime',
                      'is_reservation', 'reservation_send_time', 'is_reservation_endTime', 'goods_recommend',
                      'goods_recommend_id',
                      'goods_introduction', 'goods_distribution_text', 'goods_command', 'goods_recommend_image']
            if sql_data:
                data = ProJosn(sql_data,header,type='list')
            else:
                data = []

            return json({'code': 200, 'message': "请求成功！",'data':{
                'list':data
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/goods/getGoods', error))
            return json({'code': 200, 'message': "请求成功！"})

class getGoodsList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db

        client_ip = request.ip
        user_id = request.app.ctx.user_id
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))

        try:
            sql = f"""
                select subtitle,categoryId,goodsDetails,goodsDetailsJson,goodsName,goodsSkuJson,goodsPrice,goodsType,goodsViewCount,limitNum,memberPrice,previewUrl,retirementRule,
                rotationImgsJson,scribePrice,stockNum,contents,businessId,goods_id,paypal_type,order_type,rewardIntegral,distributionFee,
                label_ids,goodsSkuType,goods_type,goods_unit,goods_unit_num,goods_code,goods_status,goods_number,goods_barCode,goods_volume,distributionType,goods_sales,sort,gift_coupons_id,
                serviceGuarantee_id,member_see,start_shopping,reservation_startTime,reservation_endTime,is_reservation,reservation_send_time,is_reservation_endTime,goods_recommend,goods_recommend_id,
                goods_introduction,goods_distribution_text,goods_command,goods_recommend_image from goods where 
                merchant_id='{user_id}' and goodsStatus='{'1'}'
            """
            sql = sqlOrder(sql, 'ctime')
            sql = sqlPaging(pageNum, pageSize, sql)
            sql_data = db.find_all(sql)
            header = ['subtitle','categoryId','goodsDetails','goodsDetailsJson','goodsName','goodsSkuJson','goodsPrice','goodsType','goodsViewCount','limitNum','memberPrice','previewUrl','retirementRule',
                'rotationImgsJson','scribePrice','stockNum','contents','businessId','goods_id','paypal_type','rewardIntegral',
                      'distributionFee',
                      'label_ids', 'goodsSkuType', 'goods_type', 'goods_unit', 'goods_unit_num', 'goods_code',
                      'goods_status',
                      'goods_number', 'goods_barCode', 'goods_volume', 'distributionType', 'goods_sales', 'sort',
                      'gift_coupons_id',
                      'serviceGuarantee_id', 'member_see', 'start_shopping', 'reservation_startTime',
                      'reservation_endTime',
                      'is_reservation', 'reservation_send_time', 'is_reservation_endTime', 'goods_recommend',
                      'goods_recommend_id',
                      'goods_introduction', 'goods_distribution_text', 'goods_command', 'goods_recommend_image']
            if sql_data:
                data = ProJosn(sql_data,header,type='list')
            else:
                data = []

            return json({'code': 200, 'message': "请求成功！",'data':{
                'list':data
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/goods/getGoods', error))
            return json({'code': 200, 'message': "请求成功！"})

class extJsonGetGoods(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db

        client_ip = request.ip
        user_id = request.app.ctx.user_id
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        businessId = request.args.get('businessId', '')
        extJson =  request.args.get('extJson', '')
        try:

            sql = f"""
                select subtitle,categoryId,goodsDetails,goodsDetailsJson,goodsName,goodsSkuJson,goodsPrice,goodsType,goodsViewCount,limitNum,memberPrice,previewUrl,retirementRule,
                rotationImgsJson,scribePrice,stockNum,contents,businessId,goods_id,paypal_type,order_type,rewardIntegral from goods where 
                merchant_id='{user_id}' and extJson='1' and goodsStatus='{'1'}' and businessId='{businessId}' or businessId='' 
            """

            sql = sqlOrder(sql, 'ctime')
            sql = sqlPaging(pageNum, pageSize, sql)
            sql_data = db.find_all(sql)
            header = ['subtitle','categoryId','goodsDetails','goodsDetailsJson','goodsName','goodsSkuJson','goodsPrice','goodsType','goodsViewCount','limitNum','memberPrice','previewUrl','retirementRule',
                'rotationImgsJson','scribePrice','stockNum','contents','businessId','goods_id','paypal_type','order_type','rewardIntegral']
            if sql_data:
                data = ProJosn(sql_data,header,type='list')
            else:
                data = []



            return json({'code': 200, 'message': "请求成功！",'data':{
                'list':data
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/goods/getGoods', error))
            return json({'code': 200, 'message': "请求成功！"})

class getCategoryGoods(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db

        client_ip = request.ip
        user_id = request.app.ctx.user_id
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        category_id = request.args.get('category_id', '')
        try:

            sql = f"""
                select subtitle,categoryId,goodsDetails,goodsDetailsJson,goodsName,goodsSkuJson,goodsPrice,goodsType,goodsViewCount,limitNum,memberPrice,previewUrl,retirementRule,
                rotationImgsJson,scribePrice,stockNum,contents,businessId,goods_id,paypal_type,order_type,rewardIntegral from goods where 
                merchant_id='{user_id}' and goodsStatus='{'1'}' and categoryId like '%{category_id}%'
            """

            sql = sqlOrder(sql, 'ctime')

            sql = sqlPaging(pageNum, pageSize, sql)

            sql_data = db.find_all(sql)

            header = ['subtitle','categoryId','goodsDetails','goodsDetailsJson','goodsName','goodsSkuJson','goodsPrice','goodsType','goodsViewCount','limitNum','memberPrice','previewUrl','retirementRule',
                'rotationImgsJson','scribePrice','stockNum','contents','businessId','goods_id','paypal_type','order_type','rewardIntegral']
            if sql_data:
                data = ProJosn(sql_data,header,type='list')
            else:
                data = []

            return json({'code': 200, 'message': "请求成功！",'data':{
                'list':data
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/goods/getCategoryGoods', error))
            return json({'code': 200, 'message': "请求成功！"})

class getCategoryHome(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表

        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = request.args.get('keyword', '')
        user_id = request.args.get('user_id', '') or request.app.ctx.user_id

        try:
            sql = f"""
                select id,businessId,categoryDesc,categoryName,image,pid,grade,status,ctime from category where merchant_id='{user_id}' and recommend=1
            """
            tol = f""" SELECT COUNT(*) FROM category where merchant_id='{user_id}' and recommend=1 """

            if keyword:
                sql += f" and  categoryName LIKE '%{keyword}%' "
                tol += f" and  categoryName LIKE '%{keyword}%' "
            tol_data = db.find_one(tol)
            ordersql = sqlOrder(sql)
            group_sql = sqlPaging(pageNum,pageSize,ordersql)
            data = db.find_all(group_sql)
            if data:
                dataList = ProJosn(data, sql, 'sql')
            else:
                dataList = []
            return json({'code': 200,
                        'data':{
                            'list':dataList,
                            'total':tol_data[0]
                        },
                        'message': "请求成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/category/getCategoryHome', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)

class getGoodsDetails(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        client_ip = request.ip
        user_id = request.app.ctx.user_id
        goods_id = request.args.get('goods_id', '')
        try:
            sql = f"""
                            select keywords,goodsEndingTime,goodsBeginTime,limitNum_type,is_limitNum,goodsWeight,id,goods_id,businessId,extJson,categoryId,
                            goodsSkuJson,goodsPrice,goodsStatus,goodsType,limitNum,goodsName,memberPrice,previewUrl,rewardIntegral,rotationImgsJson,
                            scribePrice,stockNum,contents,status,subtitle,ctime,goodsViewCount,paypal_type,distributionFee,
                            label_ids,goodsSkuType,goods_type,goods_unit,goods_unit_num,goods_code,goods_status,goods_number,goods_barCode,goods_volume,distributionType,goods_sales,sort,gift_coupons_id,
                            serviceGuarantee_id,member_see,start_shopping,reservation_startTime,reservation_endTime,is_reservation,reservation_send_time,is_reservation_endTime,goods_recommend,goods_recommend_id,
                            goods_introduction,goods_distribution_text,goods_command,goods_recommend_image
                            from goods where merchant_id='{user_id}' and goods_id='{goods_id}'
                        """
            data = db.find_all(sql)
            if data:
                header = ['keywords', 'goodsEndingTime', 'goodsBeginTime', 'limitNum_type', 'is_limitNum',
                          'goodsWeight', 'id', 'goods_id', 'businessId', 'extJson', 'categoryId',
                          'goodsSkuJson', 'goodsPrice', 'goodsStatus', 'goodsType', 'limitNum', 'goodsName',
                          'memberPrice',
                          'previewUrl', 'rewardIntegral', 'rotationImgsJson',
                          'scribePrice', 'stockNum', 'contents', 'status', 'subtitle', 'ctime', 'goodsViewCount',
                          'paypal_type', 'distributionFee',
                          'label_ids', 'goodsSkuType', 'goods_type', 'goods_unit', 'goods_unit_num', 'goods_code',
                          'goods_status',
                          'goods_number', 'goods_barCode', 'goods_volume', 'distributionType', 'goods_sales', 'sort',
                          'gift_coupons_id',
                          'serviceGuarantee_id', 'member_see', 'start_shopping', 'reservation_startTime',
                          'reservation_endTime',
                          'is_reservation', 'reservation_send_time', 'is_reservation_endTime', 'goods_recommend',
                          'goods_recommend_id',
                          'goods_introduction', 'goods_distribution_text', 'goods_command', 'goods_recommend_image'

                          ]
                dataList = ProJosn(data, header, 'list')[0]
            else:
                dataList = []
            return json({'code': 200,
                         'data': {
                             'list': dataList
                         },
                         'message': "请求成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/goods/getGoodsDetails', error))
            return json({'code': 200, 'message': "请求成功！"})
class getGoodsSales(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        user_id = request.app.ctx.user_id
        goods_id = request.args.get('goods_id','')
        sql = f"""
            select count(*) from goods_order where merchant_id='{user_id}' and goods_id='{goods_id}'
        """
        sql_order = db.find_one(sql)
        data = {
            'code': 200,
            'data':{
                'count':sql_order[0]
            },
            'message': '添加成功!'
        }
        return json(data)
class getStore(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        html_data = request.json
        client_ip = request.ip
        user_id = request.app.ctx.user_id
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        businessId = request.args.get('businessId', '')
        try:
            sql = f"""
                select businessId,plugsConfigJson,otherConfigJson,ctime,businessName from business where merchant_id='{user_id}' and status='{'normal'}'
            """

            if businessId:
                sql += f" and businessId='{businessId}' "
            sql = sqlOrder(sql, 'ctime')
            sql = sqlPaging(pageNum, pageSize, sql)
            sql_data = db.find_all(sql)
            if sql_data:
                data = ProJosn(sql_data, sql)
            else:
                data = []
            return json({'code': 200, 'message': "请求成功！",'data':{
                'list':data
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/goods/getStore', error))
            return json({'code': 200, 'message': "请求成功！"})


class getNotice(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        html_data = request.json
        client_ip = request.ip
        user_id = request.app.ctx.user_id
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        wx_Type = request.args.get('type', '')
        try:

            sql = f"""
                select id,title,startTime,endTime,image,type,content,sort,type,status from notice where merchant_id='{user_id}' and status='{'normal'}' 
            """
            if wx_Type:
                sql += f" and type = '{wx_Type}' "
            sql = sqlOrder(sql, 'sort','ASC')
            sql = sqlPaging(pageNum, pageSize, sql)
            sql_data = db.find_all(sql)
            if sql_data:
                data = ProJosn(sql_data, sql)
            else:
                data = []

            return json({'code': 200, 'message': "请求成功！",'data':{
                'list':data
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/goods/getGoods', error))
            return json({'code': 200, 'message': "请求成功！"})


class getCategoryOne(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        client_ip = request.ip
        user_id = request.app.ctx.user_id
        try:
            sql = f"""
                select id,categoryName from category where merchant_id='{user_id}' and status='{'normal'}' and pid='0'
            """
            sql_data = db.find_all(sql)
            if sql_data:
                data = ProJosn(sql_data, ['id','name'],'list')
            else:
                data = []

            return json({'code': 200, 'message': "请求成功！",'data':{
                'list':data
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/category/getCategoryOne', error))
            return json({'code': 200, 'message': "请求成功！"})
class getCategoryTow(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        CategoryList = str(request.args.get('list', 1)).split(',')
        client_ip = request.ip
        user_id = request.app.ctx.user_id
        try:
            dataList = []

            for i in CategoryList:
                sql = f"""
                    select id,categoryName,pid,image from category where merchant_id='{user_id}' and status='{'normal'}' and pid='{i}'
                """
                sql_data = db.find_all(sql)
                if sql_data:
                    dataList.append(ProJosn(sql_data, ['id','name','pid','picture'],'list'))
                else:
                    dataList.append([])
            return json({'code': 200, 'message': "请求成功！",'data':{
                'list':dataList
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/category/getCategoryOne', error))
            return json({'code': 200, 'message': "请求成功！"})


class getShoppingCart(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        keyword = request.args.get('keyword', '')
        # print(user_id,c_user_id)
        try:

            sql = """
               select id,businessId,goods_id,openid,goods_quantity,goods_price,goods_name,goods_image,goods_sku,goods_subtitle,status,ctime from goods_shopping_cart where merchant_id=%s and openid=%s
            """
            tol = f""" SELECT COUNT(*) FROM goods_shopping_cart where merchant_id='{user_id}' and openid='{openid}' """
            if keyword:
                sql += f" and  goods_name LIKE '%{keyword}%' "
                tol += f" and  goods_name LIKE '%{keyword}%' "
            shoppingsql = sqlOrder(sql)
            sql = sqlPaging(pageNum, pageSize, shoppingsql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql, (user_id,openid))

            data = ProJosn(data, sql)

            return json({'code': 200, 'message': "请求成功!", 'data': {
                'list': data,
                'total': tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/getShoppingCart/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class DelShoppingCart(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = f"delete from goods_shopping_cart where merchant_id='{user_id}' "

            sum = 0
            for i in (html_data['dataList']):
                if sum == 0:
                    sql += f" and id={i['id']} "
                else:
                    sql += f" or id={i['id']} "
            db.delete(sql)

            data = {
                'code': 200,
                'message': '删除成功!'
            }
            return json(data)

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/shoppingCartDelete/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class getShoppingCartNum(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        client_ip = request.ip
        try:
            tol = f""" SELECT COUNT(*) FROM goods_shopping_cart where merchant_id='{user_id}' and openid='{openid}' """
            tol_data = db.find_one(tol)

            return json({'code': 200, 'message': "请求成功!", 'data': {
                'num': tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/getShoppingCartNum/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


class getOrderList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = (request.args.get('keyword', ''))
        payStatus = int(request.args.get('payStatus', 10))
        print(12312312,payStatus)
        try:
            sql = f"""
                   select goods_order.goodsQuantity,goods_order.payStatus,goods_order.id,goods_order.order_id,goods_order.business_id,
                    goods_order.goods_id,goods_order.goods_sku,goods_order.order_type,goods_order.paypal_type,goods_order.distribution_type,goods_order.total_money,
                    goods_order.goods_money,goods_order.utime,goods_order.ctime,goods_order.paypalDetails,goods.goodsName,goods.previewUrl,goods_order.goods_info,goods_order.business_info,goods_order.user_info from goods_order 
                    JOIN goods on goods_order.goods_id=goods.goods_id where goods_order.merchant_id='{user_id}' and goods_order.wechat_openid='{openid}'
                """

            # 切换订单类型
            if payStatus != 10:
                sql += f" and goods_order.payStatus={payStatus} "

            # 总数据
            tol = f""" SELECT COUNT(*) from goods_order 
                    JOIN goods on goods_order.goods_id=goods.goods_id where goods_order.merchant_id='{user_id}' and goods_order.wechat_openid='{openid}' """

            # 切换订单类型
            if payStatus != 10:
                tol += f" and goods_order.payStatus={payStatus} "

            # 搜索条件
            if keyword:
                sql += f" and  goods_order.goods_id LIKE '%{keyword}%' or goods_order.business_id LIKE '%{keyword}%' or goods_order.order_id LIKE '%{keyword}%' or goods.goodsName LIKE '%{keyword}%' "
                tol += f" and  goods_order.goods_id LIKE '%{keyword}%' or goods_order.business_id LIKE '%{keyword}%' or goods_order.order_id LIKE '%{keyword}%' or goods.goodsName LIKE '%{keyword}%' "



            sql = sqlOrder(sql, 'ctime')

            sql = sqlPaging(pageNum, pageSize, sql)

            title_list = ['goodsQuantity', 'payStatus', 'id', 'order_id', 'business_id', 'goods_id', 'goods_sku', 'order_type',
                          'paypal_type',
                          'distribution_type', 'total_money', 'goods_money', 'utime', 'ctime', 'paypalDetails',
                          'goodsName', 'previewUrl','goods_info','business_info','user_info'
                          ]
            data = db.find_all(sql)

            tol_data = db.find_one(tol)

            if data:
                dataList = ProJosn(data, title_list, 'list')
            else:
                dataList = []

            return json({
                'code': 200,
                'data': {
                    'list': dataList,
                    'total': tol_data[0]
                },
                'message': "请求成功!"
            })

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/order/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


class getBalance(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.args.get('user_id') or request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))

        try:
            sql = f"""
                  select id,currency_balance,recharge_type_id,payment_cash,give_cash,recharge_type from rechargeshow  where merchant_id='{user_id}'
              """
            sql = sqlOrder(sql,'sort','ASC')
            sql = sqlPaging(pageNum,pageSize,sql)
            data = db.find_all(sql)

            if data:
                data = ProJosn(data, sql)
            else:
                data = []

            return json({'code': 200,
                         'data': {
                             'list':data,

                         },
                         'message': "请求成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/getBalance/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


# 会员列表
class getMemberVip(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        user_id =  request.args.get('user_id', '') or request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum',1))
        pageSize = int(request.args.get('pageSize',10))
        keyword = request.args.get('keyword', '')
        try:
            sql = f"""
                select level_id,status,title,type,level_score,level_order,level_money,level_experience,level_payment,level_payday,level_logo,discount,sort from user_level where merchant_id='{user_id}'
            """

            tol = f""" SELECT COUNT(*) FROM user_level where merchant_id='{user_id}' """
            if keyword:
                sql += f" and  title LIKE '%{keyword}%' or level_id LIKE '{keyword}' "
                tol += f" and  title LIKE '%{keyword}%' or level_id LIKE '{keyword}' "
            sql = sqlOrder(sql,'sort','ASC')
            sql = sqlPaging(pageNum,pageSize,sql)
            data = db.find_all(sql)
            data = ProJosn(data,sql)
            tol_data = db.find_one(tol)
            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
                'total':tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/memberCharge/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


# 服务保障查询
class serviceGuaranteeList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        user_id =  request.args.get('user_id', '') or request.app.ctx.user_id
        client_ip = request.ip
        ids = request.args.get('ids','')
        try:
            sql = f"""
                select sort,title,details,icon from serviceGuarantee where merchant_id='{user_id}'
            """

            if ids:
                sums = 0
                for i in (ids.split(',')):

                    if sums == 0:
                        sql += f" and id={int(i)} "
                    else:
                        sql += f" or id={int(i)} "
                    sums += 1
            else:
                return json({'code': 500, 'message': "未找到服务保障数据!"})
            sql = sqlOrder(sql,'sort','ASC')
            data = db.find_all(sql)
            data = ProJosn(data,sql)

            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/serviceGuaranteeDetails/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

# 标签查询
class mallGoodsLabel(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        user_id =  request.args.get('user_id', '') or request.app.ctx.user_id
        client_ip = request.ip
        ids = request.args.get('ids','')
        useType = request.args.get('useType','')

        try:
            sql = f"""
                select labelName,labelType,setting,fontColor,backgroundColor,borderColor,sort,image from goods_label where merchant_id='{user_id}' and useType='{useType}'
            """

            if ids:
                sums = 0
                for i in (ids.split(',')):

                    if sums == 0:
                        sql += f" and id={int(i)} "
                    else:
                        sql += f" or id={int(i)} "
                    sums += 1
            else:
                return json({'code': 500, 'message': "未找到标签数据!"})
            sql = sqlOrder(sql,'sort','ASC')
            data = db.find_all(sql)
            data = ProJosn(data,sql)

            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/serviceGuaranteeDetails/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)